# -*- coding: utf-8 -*-
"""A Namespace describes a QPBuild Namespace. These entities are created by
polling the namespace server(s) and merging the results into the database.
"""

from sqlalchemy import *
from sqlalchemy.orm import mapper, relation
from sqlalchemy import Table, ForeignKey, Column
from sqlalchemy.types import Integer, Unicode

from abserver.model import DeclarativeBase, metadata, DBSession

class BuildView(DeclarativeBase):
    # table options
    __tablename__ = 'buildview'

    # columns
    buildview_id = Column(Integer, primary_key=True, autoincrement=True)
    buildview_name = Column(Unicode(64), nullable=False)
    buildview_description = Column(Unicode(), nullable=True)
    # View criteria
    buildview_build_live = Column(Integer)
    buildview_start_time = Column(DateTime)
    buildview_end_time = Column(DateTime)
    buildview_age = Column(Integer)

    buildview_componet_id = Column(Integer, ForeignKey('component.component_id'))
    buildview_branch_id = Column(Integer, ForeignKey('branch.branch_id'))

    # relationships
    buildview_component = relation('Component', backref='buildviews')
    buildview_branch = relation('Branch', backref='buildviews')
    ## buildblessings


##    def __init__(self, name, description=None, component=None, branch=None, bless_levels=[], build_live=None,
##                 start_time=None, end_time=None, age=None):
##        self.buildview_name = name
##        self.buildview_description = description
##        self.buildview_component = component
##        self.buildview_branch = branch
##        self.bless_levels = bless_levels
##        self.buildview_build_live = build_live
##        self.buildview_start_time = start_time
##        self.buildview_end_time = end_time
##        self.buildview_age = age
##        self.flush()

    @classmethod
    def get_buildview(cls, name, description=None, component=None, branch_id=None, bless_levels=[], build_live=None,
                      start_time=None, end_time=None, age=None):
        buildview = DBSession.query(cls).filter(cls.buildview_name==name).first()
        if not buildview:
            buildview = cls(name, description, component, branch_id, bless_levels, build_live, start_time, end_time, age)
            DBSession.add(buildview)
        return buildview
    
    @classmethod
    def get(cls, buildview_id):
        view = DBSession.query(cls).filter(cls.buildview_id==buildview_id).first()
        return view
